import CryptoJS from "crypto-js";
import {
    ElMessage,
    ElMessageBox
} from 'element-plus'

// 创建签名的函数
export function createSign(userId, timestamp) {
    const rawString = `${userId}${timestamp}`;
    const md5Hash = CryptoJS.MD5(rawString).toString();
    return md5Hash;
};

// 心跳消息内容和发送间隔
const heartBeatMsg = {
    msgType: "heartbeat"
};
const heartBeatInterval = 60000; // 60秒

// 心跳定时器
let heartBeatTimer = null;

// 启动心跳
export function startHeartBeat(socket) {
    heartBeatTimer = setInterval(() => {
        // 检查WebSocket状态
        if (socket.readyState === WebSocket.OPEN) {
            // 发送心跳消息
            socket.send(JSON.stringify(heartBeatMsg));
        } else {
            // 如果连接已关闭，清除定时器
            clearInterval(heartBeatTimer);
        }
    }, heartBeatInterval);
}

export function getSocket(userId, timestamp, sign) {
    const socket = new WebSocket(
        `wss://cipp.ecaray.com/cipp-ws?serial=${userId}&timestamp=${timestamp}&sign=${sign}`
    );
    socket.onopen = (e) => {
        console.log("WebSocket连接已建立");
        startHeartBeat(socket);
    };

    // 当WebSocket接收到消息时
    socket.onmessage = (event) => {
        // 可以在这里检查消息类型，看是否是心跳响应
        const data = JSON.parse(event.data);
        if (data.msgType === "forced_offline") {
            // alert("当前账号在其他地方登录");
            ElMessageBox.alert("当前账号在其他地方登录", "温馨提示", {
                confirmButtonText: '确定',
                callback: () => {
                    // window.location.href = "/#/"; //本地
                    window.location.href = "/nc/iop/#/"; //测试
                }
            })
        }
        if (data.msgType === "heartbeat") {
            console.log("收到心跳响应");
        }
    };

    // 当WebSocket连接关闭时
    socket.onclose = (event) => {
        console.log("WebSocket连接已关闭");
        clearInterval(heartBeatTimer); // 清除心跳定时器
    };

    // 当WebSocket发生错误时
    socket.onerror = (error) => {
        console.error("WebSocket发生错误:", error);
        clearInterval(heartBeatTimer); // 清除心跳定时器
        // 可以选择在这里尝试重新连接
    };

    return socket;
}